<!--
 * @description  : 案件-立案报告文书
 * @descriptionDetail: 案件-立案报告文书
 * @copyright    : 浙江烟草
 * @author       : sy
 * @create       : 2022-07-25 15:43:11
-->
<template>
	<view class="page">
	  <!-- #ifdef H5-ONLY -->
	  <theme-navbar :is-white="false" :title="navTitle" :custom-back="goBack" style="z-index: 99999">
		<view class="theme-color" @click="printOrDown(state.canEdit)">
		  {{ state.canEdit?'预览':'打印' }}
		</view>
	  </theme-navbar>
		  <!-- #endif -->
		  <!-- #ifdef H5-WECHAT || H5-EMP -->
		  <fab-button :content="state.canEdit?fContent:fContents" @fabtrigger="fabtrigger" />
		  <!-- #endif -->
	  <view class="top-title-content">
		<view class="main-title">
		  {{ caseData.orgShortName }}
		</view>
		<view class="sub-title">
		  立案报告表
		</view>
		<view class="content-detail">
		  {{ caseData.orgAbbr }}烟立﹝
		  <u-input
			:clearable="false"
			type="number"
			class="doc-no"
			:disabled="!state.canEdit"
			placeholder="请输入"
			v-model="caseData.docYear"
		  />﹞
		  <u-input
			type="text"
			:clearable="false"
			class="doc-no"
			:disabled="!state.canEdit"
			placeholder="请输入"
			v-model="caseData.docNo"
		  />号
		</view>
	  </view>
	  <u-gap height="20" bg-color="#f2f2f2"></u-gap>
	  <view class="main-content">
		<u-form class="" :model="caseData" :error-type="errorType" :label-position="labelPosition" ref="uForm">
		  <u-form-item
			label="案由"
			:label-position="labelPosition"
			:required="true"
			right-icon="arrow-right"
			prop="causeOfAction"
			ref="caseChangeRef"
		  >
			<u-input
			  type="textarea"
			  height="35"
			  :auto-height="true"
			  placeholder="请选择"
			  :disabled="true"
			  v-model="caseData.causeOfAction"
			  @click="()=>{if(state.canEdit) causeOfActionHandle()}"
			/>
		  </u-form-item>
		  <u-form-item label="案件来源" :required="true" :label-width="labelWidth">
			<dic-input
			  input-align="right"
			  :keyWord="$u.dic.DIC_KEYS.CASE_SOURCE"
			  :dicCode="caseData.caseFrom"
			  :border="border"
			  type="select"
			  :select-open="dicSelectOpen($u.dic.DIC_KEYS.CASE_SOURCE)"
			  placeholder="请选择"
			  :disabled="!state.canEdit"
			  v-model="caseData.caseFromName"
			  @changeInputModelData="(name)=>{$set(caseData, 'caseFromName', name)}"
			  @click="showDic($u.dic.DIC_KEYS.CASE_SOURCE,caseData.caseFrom)"
			/>
		  </u-form-item>
		  <u-form-item
			label="案发时间"
			:label-width="labelWidth"
			prop="caseTime"
			right-icon="arrow-right"
			ref="changeRefS"
		  >
			<u-input
			  placeholder="请选择"
			  input-align="right"
			  :disabled="true"
			  :clearable="false"
			  v-model="caseData.caseTime"
			  @click="()=>{if(state.canEdit) clicDatekHandle('isShowTime')}"
			/>
		  </u-form-item>
		  <u-form-item label="案发地点" label-width="labelWidth">
			<u-input
			  placeholder="请输入"
			  input-align="right"
			  :disabled="!state.canEdit"
			  v-model="caseData.casePlace"
			/>
		  </u-form-item>
		  <u-form-item :label="caseData.partyType ==2 ?'法人代表（负责人）':'自然人姓名'" :label-width="labelWidth">
			<u-input
			  placeholder="请输入"
			  input-align="right"
			  :disabled="!state.canEdit"
			  v-model="caseData.party"
			/>
		  </u-form-item>
		  <u-form-item :label="caseData.partyType==2?'法人或组织名称':'字号名称'" :label-width="labelWidth">
			<u-input
			  placeholder="请输入"
			  input-align="right"
			  :disabled="!state.canEdit"
			  v-model="caseData.companyName"
			/>
		  </u-form-item>
		  <u-form-item label="证件类型" :label-width="labelWidth">
			<dic-input
			  input-align="right"
			  :keyWord="$u.dic.DIC_KEYS.IDCARD_TYPE"
			  :dicCode="caseData.idCardType"
			  :border="border"
			  type="select"
			  :select-open="dicSelectOpen($u.dic.DIC_KEYS.IDCARD_TYPE)"
			  placeholder="请选择"
			  :disabled="!state.canEdit"
			  v-model="caseData.idCardTypeName"
			  @changeInputModelData="(name)=>{$set(caseData, 'idCardTypeName', name)}"
			  @click="showDic($u.dic.DIC_KEYS.IDCARD_TYPE,caseData.idCardType)"
			/>
		  </u-form-item>
		  <u-form-item label="证件号码" :label-position="labelPosition" prop="idCard">
			<u-input placeholder="请输入证件号码" :disabled="!state.canEdit" v-model="caseData.idCard" />
		  </u-form-item>
		  <u-form-item label="地址" :label-position="labelPosition">
			<u-input placeholder="请输入" :disabled="!state.canEdit" v-model="caseData.idCardAddress" />
		  </u-form-item>
		  <u-form-item label-width="auto" :border-bottom="false" label="案情摘要" label-position="left" prop="caseBrief">
			<u-icon
			  slot="right"
			  customPrefix="csbi-icon"
			  name="moban"
			  size="40"
			  :color="$theme.u_type_primary"
			  @click="tapFieldPress('caseBrief')"
			></u-icon>
		  </u-form-item>
		  <u-form-item label="">
			<u-input
			  type="textarea"
			  placeholder="请输入"
			  :disabled="!state.canEdit"
			  v-model="caseData.caseBrief"
			/>
		  </u-form-item>
		</u-form>
	  </view>
	  <!-- 承办人意见 -->
	  <view>
		<u-gap height="20" bg-color="#f2f2f2"></u-gap>
		<view class="audit-content">
		  <view class="audit-title" style="display: inline-flex;flex-direction: row;width: 100%;justify-content: space-between;align-items: center;">
			<text>承办人意见</text>
			<u-icon
			  customPrefix="csbi-icon"
			  name="moban"
			  size="40"
			  :color="$theme.u_type_primary"
			  @click="tapFieldPress('undertakerAdvice')"
			></u-icon>
		  </view>
		  <view class="audit-text">
			<u-input
			  type="textarea"
			  placeholder="请输入"
			  :disabled="!state.canEdit"
			  v-model="caseData.undertakerAdvice"
			/>
		  </view>
		  <view class="audit-person">
			<u-input
			  placeholder="请选择"
			  input-align="right"
			  :disabled="true"
			  :clearable="false"
			  v-model="caseData.undertaker"
			  @click="()=>{if(state.canEdit) personSelectShow = true}"
			/>
		  </view>
		  <view class="audit-date">
			<u-input
			  placeholder="请选择"
			  input-align="right"
			  :disabled="true"
			  :clearable="false"
			  v-model="caseData.undertakerTime"
			  @click="()=>{if(state.canEdit) clicDatekHandle('isShowUndertakerTime')}"
			/>
		  </view>
		</view>
	  </view>
	  <view class="audit-box" v-if="!state.canEdit">
		<view v-for="(ao,index) in approves" :key="index">
		  <u-gap height="20" bg-color="#f2f2f2"></u-gap>
		  <view class="audit-content">
			<view class="audit-title">
			  <text class="audit-require">
				*
			  </text>{{ ao.flowNode.displayName }}
			</view>
			<view class="audit-text">
			  <u-input
				type="textarea"
				placeholder=""
				:disabled="true"
				v-model="caseData['_approveInfo'+ao.gfaCode]"
			  />
			</view>
			<view class="audit-person">
			  <u-input
				placeholder="签名"
				input-align="right"
				:disabled="true"
				:clearable="false"
				v-model="caseData['_approvePersonName'+ao.gfaCode]"
			  />
			</view>
			<view class="audit-date">
			  <u-input
				placeholder="年  月  日"
				input-align="right"
				:disabled="true"
				:clearable="false"
				v-model="caseData['_approveDate'+ao.gfaCode]"
			  />
			</view>
		  </view>
		</view>
	  </view>
	  <view class="bottom-btn-info" v-if="state.canEdit">
		<u-row gutter="16">
		  <u-col span="6">
			<u-button plain type="primary" @click="submitBtn('save')">
			  保存
			</u-button>
		  </u-col>
		  <u-col span="6">
			<u-button type="primary" @click="submitBtn('submit')">
			  提交
			</u-button>
		  </u-col>
		</u-row>
	  </view>
	  <!-- 人员选择 -->
	  <u-popup mode="bottom" height="80%" v-model="personSelectShow">
		<person-selection :params="psParam" @choose="handlerChoosePerson"></person-selection>
	  </u-popup>
	  <u-picker mode="time" :params="paramsDate" v-model="isShowTime" @confirm="changeDate('caseTime',$event)">
	  </u-picker>
	  <u-picker
		mode="time"
		:params="paramsDate"
		v-model="isShowUndertakerTime"
		@confirm="changeDate('undertakerTime',$event)"
	  ></u-picker>
	  <u-picker
		mode="time"
		:params="paramsDate"
		v-model="isShowDate01"
		@confirm="changeDate('_approveDate01',$event)"
	  ></u-picker>
	  <u-picker
		mode="time"
		:params="paramsDate"
		v-model="isShowDate02"
		@confirm="changeDate('_approveDate02',$event)"
	  ></u-picker>
	  <dic-choice
		:keyWord="dicKeyWords"
		:currentSelect="dicCurrentSelect"
		v-model="dicShow"
		@confirm="selectDicConfirm"
	  ></dic-choice>
	  <u-popup mode="bottom" height="80%" v-model="showFieldTpl">
		<doc-form-content-tep
		  :params="fieldParam"
		  formName="caseData"
		  :fieldkey="fieldKey"
		  @choice="choiceFieldTpl"
		></doc-form-content-tep>
	  </u-popup>
	</view>
  </template>
  
  <script>
	  import caseCommon from "../caseCommonMixin.js";
	  import officeService from "@/service/case/office.service.js";
	  import caseService from "@/service/case/case.service";
	  import DicChoice from "@/components/dic_choice.vue";
	  import DicInput from "@/components/dic_input.vue";
	  import {
		  IDENTITY_TYPE,
	  } from "@/common/common_enum.js";
	  import PersonSelection from "@/pages/case/components/personSelection.vue";
	  import DocFormContentTep from "../components/docFormContentTemplate.vue";
	  import fabButton from '@/components/uni-fab.vue';
  
	  export default {
		  components: {
			  "dic-choice": DicChoice,
			  "dic-input": DicInput,
			  PersonSelection,
			  DocFormContentTep,
			  fabButton
		  },
		  mixins: [caseCommon, ],
		  data() {
			  return {
				  IDENTITY_TYPE,
				  caseParam: {}, // 上个页面传过来的案件信息
				  dicShow: false, // dic_select 是否显示
				  dicKeyWords: "", // dic 关键字
				  dicCurrentSelect: "", // dic 当前选择项
				  border: false,
				  errorType: ['border-bottom', 'message', ],
				  labelPosition: "top",
				  labelWidth: '280',
				  rules: {
					  causeOfAction: [{
						  required: true,
						  message: '请选择案由',
						  trigger: ['change', 'blur', ],
					  }, ],
					  idCard: [{
						  validator: () => {
							  // 证件类型选择身份证，校验身份证号
							  if ((this.caseData.idCardType == IDENTITY_TYPE.IDENTIFICATION || this.caseData
									  .idCardType == IDENTITY_TYPE.TEMID)) {
								  if (this.$u.test.isEmpty(this.caseData.idCard)) {
									  return false;
								  } else {
									  return this.$u.test.idCard(this.caseData.idCard);
								  }
							  } else {
								  return true;
							  }
						  },
						  message: '身份证号码不正确',
						  trigger: ['change', 'blur', ],
					  }, ],
				  },
				  caseData: {}, // 立案报告数据
				  isAction: false,
				  isShowTime: false, // 是否显示案发时间
				  isShowUndertakerTime: false, // 是否显示承办时间
				  isShowDate01: false,
				  isShowDate02: false,
				  paramsDate: {
					  year: true,
					  month: true,
					  day: true,
					  hour: true,
					  minute: true,
					  second: true,
					  timestamp: true,
				  },
				  docIns: {}, // 文书实例信息
				  approves: [], // 审核审批信息
				  doc: {},
				  personSelectShow: false,
				  isApprovePerson: false, // 是否是审核人
				  psParam: {},
				  employeeLst: [],
				  fContent: [{
					  iconPath: require('@/static/oview.png'),
					  selectedIconPath: require('@/static/oview.png'),
					  text: '预览',
					  active: false,
				  }],
				  fContents: [{
					  iconPath: require('@/static/dy.png'),
					  selectedIconPath: require('@/static/dy.png'),
					  text: '打印',
					  active: false,
				  }]
			  }
		  },
		  onReady() {
			  this.$refs.uForm.setRules(this.rules);
		  },
		  onLoad() {
			  this.caseParam = this.getRouteParam();
			  this.psParam.caseUuid = this.caseParam.caseUuid;
			  console.log('参数：' + JSON.stringify(this.caseParam));
		  },
		  watch: {
			  isShowTime() {
				  this.$refs.changeRefS.validation();
			  },
		  },
		  mounted() {
			  this.docStep((docInfo) => {
				  this.doc = docInfo;
				  this.setRightBtns();
			  });
			  this.initDocData();
		  },
		  methods: {
			  initDocData() {
				  officeService.docFields(this.caseParam.docUuid, true).then(docConfigs => {
					  if (docConfigs.success) {
						  this.docFields = [...docConfigs.data, ];
						  this.$modal.showLoading("文书加载中...");
						  let self = this;
						  // 承办人意见，流程信息
						  Promise.all([
							  officeService.docRegRep({
								  id: this.caseParam.id,
								  docUuid: this.caseParam.docUuid,
								  bizUuid: this.caseParam.bizUuid,
							  }),
							  officeService.approves({
								  id: this.caseParam.id,
								  docUuid: this.caseParam.docUuid,
							  }),
						  ]).then(_docs => {
							  console.log("数据", _docs);
							  let [tiInfo, rs, ] = [{}, {}, ];
							  if (_docs[0].data.length === 2) {
								  tiInfo = _docs[0].data[0];
								  rs = _docs[0].data[1];
								  Object.keys(tiInfo).forEach(key => {
									  rs[key] = tiInfo[key];
								  });
							  } else {
								  rs = _docs[0].data[0];
							  }
							  this.caseData = rs;
							  this.approves = _docs[1].data;
							  console.log(this.caseData);
							  console.log(this.approves);
							  this.approves.forEach((item) => {
								  this.caseData['_approveInfo' + item.gfaCode] = item.approveInfo ||
									  '';
								  this.caseData['_approvePersonUuid' + item.gfaCode] = item
									  .approvePersonUuid || '';
								  this.caseData['_approvePersonName' + item.gfaCode] = item
									  .approvePersonName || '';
								  this.caseData['_approveDate' + item.gfaCode] = item.approveDate ?
									  item.approveDate : (item.step == item.flowNode.nodeCode ?
										  this.$u.date(Date.now(), 'yyyy年mm月dd日') : '');
							  });
							  self.$modal.hideLoading();
						  }, (err) => {
							  self.$modal.hideLoading();
							  self.$u.toast(err);
						  });
					  } else {
						  this.$u.toast(docConfigs.msg);
					  }
				  });
			  },
			  // 设置右侧标题
			  setRightBtns() {
				  // #ifdef H5-DINGDING
				  this.$deviceApi.setRight(this.state.canEdit ? '预览' : '打印', () => {
					  this.printOrDown(this.state.canEdit);
					  this.setRightBtns();
				  }, true, true);
				  // #endif
			  },
			  fabtrigger(btn) {
				  if (btn.index == 0) {
					  this.printOrDown(this.state.canEdit);
				  }
			  },
			  // 打印/预览
			  printOrDown(flag) {
				  if (flag) {
					  // 调接口预览
					  this.submitBtn('preview');
				  } else {
					  this.downloadFile(this.doc.pdfFileId);
				  }
			  },
			  downloadFile(fileId, titleName, isDownload) {
				  let pdfIds = fileId;
				  if (!pdfIds) {
					  this.$u.toast("没有文书");
					  return;
				  }
				  this.setRouteParam({
					  fileId: pdfIds,
					  fileName: titleName,
					  isDownload: isDownload,
				  });
				  this.$u.route('pages/commonPage/printerComponent');
			  },
			  // 数据字典组件选择事件
			  dicSelectOpen(keyWord) {
				  if (this.dicKeyWords == keyWord && this.dicShow) {
					  return true;
				  }
				  return false;
			  },
			  showDic: function(key, cur) {
				  if (!this.state.canEdit) return;
				  if (this.dicShow) return;
				  this.dicKeyWords = key;
				  this.dicCurrentSelect = cur;
				  this.dicShow = true;
			  },
			  selectDicConfirm: function(e) {
				  // 类型
				  if (this.dicKeyWords == this.$u.dic.DIC_KEYS.IDCARD_TYPE) {
					  this.caseData.idCardTypeName = e[0].label;
					  this.caseData.idCardType = e[0].extra.bcbCode;
					  this.caseData.idCardType && this.caseData.idCard && (this.caseData.idCard = "");
				  } else if (this.dicKeyWords == this.$u.dic.DIC_KEYS.CASE_SOURCE) {
					  this.caseData.caseFromName = e[0].label;
					  this.caseData.caseFrom = e[0].extra.bcbCode;
				  }
			  },
			  // 案由点击事件
			  causeOfActionHandle() {
				  this.isAction = true;
				  this.$u.route('pages/case/components/casePropertySelection');
			  },
			  // 选择案由、物品清单返回的数据
			  updateBackState(param) {
				  console.log('====', param.caseSelectionData);
				  // 案由
				  if (param.caseSelectionData) {
					  let names = [];
					  let ids = [];
					  param.caseSelectionData.forEach((item) => {
						  names.push(item.caseProperty);
						  ids.push(item.casepropUuid);
					  });
					  this.caseData.causeOfAction = names.join(",");
					  this.caseData.casepropIds = ids.join(",");
					  this.isAction = false;
				  }
			  },
			  clicDatekHandle(type) {
				  this[type] = true;
			  },
			  changeDate(type, e) {
				  let compareDate = e.year + '-' + e.month + '-' + e.day + ' ' + e.hour + ':' + e.minute;
				  let fmt = type == 'caseTime' ? 'yyyy年mm月dd日 hh时MM分' : 'yyyy年mm月dd日';
				  this.caseData[type] = this.$u.date(new Date(compareDate).getTime(), fmt);
			  },
			  handlerChoosePerson(e) {
				  this.personSelectShow = false;
				  if (this.isApprovePerson) {
					  let nextP = [];
					  e.forEach((item) => {
						  nextP.push(item.personId);
					  });
					  this.submitDocRegRep(nextP.join(','));
				  } else {
					  this.employeeLst = [...e, ];
					  let tIds = [];
					  let tNames = [];
					  this.employeeLst.forEach(el => {
						  tIds.push(el.personUuid);
						  tNames.push(el.personName + "(" + el.leCertNo + ")");
					  });
					  this.caseData['undertakerUuids'] = tIds.join(",");
					  this.caseData['undertaker'] = tNames.join(",");
				  }
			  },
			  // 表单验证
			  validForm() {
				  let basicValid = false;
				  this.$refs.uForm.validate(valid => {
					  if (valid) {
						  basicValid = true;
						  console.log('表单验证通过');
					  } else {
						  basicValid = false;
						  console.log('表单验证失败');
					  }
				  });
				  return basicValid;
			  },
			  // 保存/提交
			  submitBtn(type) {
				  let {
					  id,
					  docUuid,
					  titemUuid,
					  gfaCode,
				  } = this.caseParam;
				  this.caseData.caseUuid = this.caseParam.caseUuid;
				  // 验证表单
				  let flag = this.validForm();
				  if (flag) {
					  if (type == 'submit') {
						  // 选择审核人
						  this.choseAuditPsr('docRegisterReport');
					  } else {
						  type == 'save' && this.$u.loading('数据保存中...');
						  officeService.saveDocRegRep(this.caseData, docUuid, titemUuid, id, this.caseParam.type).then(
							  res => {
								  this.$u.hideLoading();
								  if (res.success) {
									  this.caseData = {
										  ...this.caseData,
										  ...res.bean,
									  };
									  try {
										  if (!this.doc) this.doc = res.data[0];
									  } catch (e) {
										  console.log(e);
									  }
									  if (type == 'preview') {
										  officeService.buildLocalPunish("/build/doc-register-report", this.doc
											  .docInsUuid).then(pdfId => {
											  if (pdfId.success) {
												  this.downloadFile(pdfId.bean, "预览", false);
											  } else {
												  this.$u.toast(pdfId.msg);
											  }
										  });
									  } else {
										  this.saveBehaviorLog(0, this.caseParam, this.doc);
										  this.$u.toast(res.msg);
									  }
								  } else {
									  this.$u.hideLoading();
									  this.$u.toast(res.msg);
								  }
							  })
					  }
				  }
			  },
			  // 提交
			  submitDocRegRep(nextPersons) {
				  let {
					  id,
					  docUuid,
					  titemUuid,
					  type,
				  } = this.caseParam;
				  this.$u.loading('数据提交中...');
				  officeService.saveDocRegRep(this.caseData, docUuid, titemUuid, id, this.caseParam.type).then(res => {
					  if (res.success) {
						  this.caseData = {
							  ...this.caseData,
							  ...res.bean,
						  };
						  officeService.submitDocRegRep(this.caseData, docUuid, titemUuid, id, type, nextPersons)
							  .then(res => {
								  this.$u.hideLoading();
								  this.$u.toast(res.msg);
								  this.saveBehaviorLog(1, this.caseParam, this.doc);
								  this.backPrev({
									  paramKey: "offiList",
									  param: {
										  caseUuid: this.caseParam.bizUuid,
										  caseCode: this.caseParam.caseCode,
										  caseType: this.caseParam.caseType,
									  },
								  });
							  })
					  } else {
						  this.$u.hideLoading();
						  this.$u.toast(res.msg);
					  }
				  })
			  },
			  // 提交时选择审核人
			  choseAuditPsr(gfaCode) {
				  this.isApprovePerson = true;
				  this.psParam = {
					  min: 1,
					  selectedPsrLst: [],
					  dataHandler: (psrName) => {
						  return caseService.getNextFlowUsers({
							  page: 1,
							  limit: 20,
							  personName: psrName,
							  gfCode: gfaCode,
						  }).then(res => {
							  if (res.success) {
								  return res.data;
							  } else {
								  return [];
							  }
						  });
					  },
				  };
				  this.personSelectShow = true;
			  },
		  },
	  }
  </script>
  
  <style lang="scss" scoped>
	  @import "../case_common.scss";
  
	  .doc-no {
		  display: inline-flex;
		  height: 35px;
		  width: 60px;
		  text-align: center !important;
		  flex: none;
	  }
  </style>
  